﻿<?php if (!defined('BASEPATH'))exit('No direct script access allowed');

class Post extends MY_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model("bbs_detail_model");
        $this->load->model("bbs_article_model");
        $this->load->model("bbs_user_model");
        $this->assign("cates", $this->forummenu);
        $this->assign("module", "index");
    }
    function index() {
        if(!$this->bbs_userinfo){//未登录状态
            web_redirect("site/login.html".$this->get_next_request_url());
        }
        if($this->bbs_userinfo['user_id']){
            if($this->bbs_userinfo['mobile']==''){
                $this->assign('mobile', 0);
            }
        }
        $item = $this->db->select("*")->from("bbs_article_drafts")->where(array("authorid"=>$this->bbs_userinfo['user_id']))->get()->row_array();
        if($item){
            header("Location:".web_url("post/boxs/".$item['id']));
        }
        $user_info = $this->db->select("email")->from("users")->where(array("user_id"=>$this->bbs_userinfo['user_id']))->get()->row_array();
        $user_email = $user_info['email'] ? email_formart($user_info['email']) : "";
        $draft_number = substr(strtolower(md5(time())),22);
        $tags = $this->db->select("*")->from("bbs_article_tags")->where(array("is_recommend"=>1))->order_by("sort desc")->get()->result_array();
        //草稿箱数量
        $box_num = $this->db->select("*")->from("bbs_article_drafts")->where(array("authorid"=>$this->bbs_userinfo['user_id']))->get()->num_rows();
        //热门文章
        $hot_arts = $this->hot_art();
        
        $this->assign("user_email", $user_email);
        $this->assign("draft_number", $draft_number);
        $this->assign("box_num", $box_num);
        $this->assign("tags", $tags);
        $this->assign("hot_arts", $hot_arts);
        $this->display('post/index.html');
    }
    //添加文章
    function add(){
        if($_POST){
            if(!$this->bbs_userinfo){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "您还未登录，请先登录哦";
                echo JSON($mess);exit;
            }
            $title = isset($_POST['artTitle']) ? trim($_POST['artTitle']) : "" ;//帖子名称
            $content = isset($_POST['artContent']) ? trim($_POST['artContent']) : "" ;//帖子内容
            $cat_id = isset($_POST['artCat']) ? trim($_POST['artCat']) : "" ;//帖子类别
            $tags = isset($_POST['artTag']) ? trim($_POST['artTag']) : "" ;//帖子标签
            $email_notice = isset($_POST['is_email']) ? trim($_POST['is_email']) : 0 ;//有评论是否邮件通知
            $draftNnumber = isset($_POST['draftNnumber']) ? trim($_POST['draftNnumber']) : 0 ;//有评论是否邮件通知
            $title = strip_tags($title);
            if($title == ""){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "标题不合法，请重新输入";
                echo JSON($mess);exit;
            }
            if($content == ""){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "请输入文章内容";
                echo JSON($mess);exit;
            }
            $allergicWord = file_get_contents("http://static.tan66.com/upfiles/files/badwords.txt");
            $allergicWord = str_replace(array("\r\n", "\r", "\n"),'',$allergicWord);
            $allergicWord= explode('|',$allergicWord);
            $info=0;
            $tinfo=0;
            $sensitive = "";
            for ($i=0;$i<count($allergicWord);$i++){  
                $check = substr_count($content, $allergicWord[$i]);
                $tcheck = substr_count($title,$allergicWord[$i]);
                if($check>0){
                    $sensitive .= $allergicWord[$i];
                    $info = $check;
                    break;
                }
                if($tcheck>0){
                    $sensitive .= $allergicWord[$i];
                    $tinfo = $tcheck;
                    break;;
                }
            }  
            if($info>0 || $tcheck>0){
                $errmes['reqStatus'] = false;
                $errmes['errorMsg'] = "检查您的文章里面有非法或敏感内容:<span class='error'>".$sensitive."</span>，请修正";
                $errmes['errorCode'] = 1003;
                echo JSON($errmes);exit;
            }
            preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.bmp|\.jpeg]))[\'|\"].*?[\/]?>/i", $content, $matches);
            $thumb = $matches[1][0] ? $matches[1][0] : "";
            if($thumb){
                $result = $this->crypt->POST_Api("http://static.tan66.com/mimage/resize/270/170",array("file"=>$thumb));
                $result = json_decode($result,true);
                $thumb = $result['filename'];
            }else{
                $thumb = "http://static.tan66.com/upfiles/df.jpg";
            }
            $summary = mb_strcut(trim(strip_tags(str_replace("&nbsp;", "", $content))),0,500);
            $data = array();
            $data['authorid'] = $this->bbs_userinfo['user_id'];
            $data['title'] = $title;
            $data['content'] = $content;
            $data['summary'] = $summary;
            $data['thumb'] = $thumb;
            if(strpos($tags, "溜溜心愿")){
                $data['cate_id'] = 11;//游戏娱乐模块
            }else{
                 $data['cat_id'] = $cat_id;
            }
            $data['tags_name'] = $tags;
            $data['create_time'] = time();
            $data['status'] = 0;
            $data['month'] = date("Ym");
            $data['day'] = date("Ymd");
            $data['is_email_noitce'] = $email_notice;
            $this->db->trans_begin();//开启事务
            $insert_id = $this->bbs_article_model->insert($data);
            //删除草稿箱
            $query1 = $this->delete_draft($draftNnumber);
            //更新文章标签统计
            $tags ? $query2 = $this->update_tags($tags) : $query2 = 1;
            if($insert_id && $query1 && $query2){
                $this->db->trans_commit();//提交事务
                $mess['reqStatus'] = true;
                $mess['url'] = web_url("/p/upub/".encrypt_article_id($insert_id));
                $mess['errorMsg'] = "发布成功,请耐心等待系统的审核";
                echo JSON($mess);exit;
            }else{
                $this->db->trans_rollback();//事务回滚
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "发布失败，请稍后重试";
                echo JSON($mess);exit;
            }
        }
    }
    
    //修改文章
    function modify(){
        if($_POST){
            if(!$this->bbs_userinfo){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "您还未登录，请先登录哦";
                echo JSON($mess);exit;
            }
            $article_id = isset($_POST['articleId']) ? trim($_POST['articleId']) : 0 ;//帖子id
            $title = isset($_POST['artTitle']) ? trim($_POST['artTitle']) : "" ;//帖子名称
            $content = isset($_POST['artContent']) ? trim($_POST['artContent']) : "" ;//帖子内容
            $cat_id = isset($_POST['artCat']) ? trim($_POST['artCat']) : "" ;//帖子类别
            $tags = isset($_POST['artTag']) ? trim($_POST['artTag']) : "" ;//帖子标签
            $email_notice = isset($_POST['is_email']) ? trim($_POST['is_email']) : 0 ;//有评论是否邮件通知
            $article_id = decrypt_article_id($article_id);
            $article = $this->db->select("id,authorid,status")->from("bbs_article")->where(array("id"=>$article_id))->order_by("id desc")->get()->row_array();
            if(!$article || $article['authorid'] != $this->bbs_userinfo['user_id']){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "非法操作";
                echo JSON($mess);exit;
            }
            
            $title = strip_tags($title);
            if($title == ""){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "标题不合法，请重新输入";
                echo JSON($mess);exit;
            }
            if($content == ""){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "请输入文章内容";
                echo JSON($mess);exit;
            }
            $allergicWord = file_get_contents("http://static.tan66.com/upfiles/files/badwords.txt");
            $allergicWord = str_replace(array("\r\n", "\r", "\n"),'',$allergicWord);
            $allergicWord= explode('|',$allergicWord);
            $info=0;
            $tinfo=0;
            $sensitive = "";
            for ($i=0;$i<count($allergicWord);$i++){  
                $check = substr_count($content, $allergicWord[$i]);
                $tcheck = substr_count($title,$allergicWord[$i]);
                if($check>0){
                    $sensitive .= $allergicWord[$i];
                    $info = $check;
                    break;
                }
                if($tcheck>0){
                    $sensitive .= $allergicWord[$i];
                    $tinfo = $tcheck;
                    break;;
                }
            }  
            if($info>0 || $tcheck>0){
                $errmes['reqStatus'] = false;
                $errmes['errorMsg'] = "检查您的文章里面有非法或敏感内容:<span class='error'>".$sensitive."</span>，请修正";
                $errmes['errorCode'] = 1003;
                echo JSON($errmes);exit;
            }
            preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.bmp|\.jpeg]))[\'|\"].*?[\/]?>/i", $content, $matches);
            $thumb = $matches[1][0] ? $matches[1][0] : "";
            if($thumb){
                $result = $this->crypt->POST_Api("http://static.tan66.com/mimage/resize/270/170",array("file"=>$thumb));
                $result = json_decode($result,true);
                $thumb = $result['filename'];
            }else{
                $thumb = "http://static.tan66.com/upfiles/df.jpg";
            }
            $summary = mb_strcut(trim(strip_tags(str_replace("&nbsp;", "", $content))),0,500);
            $data = array();
            $data['title'] = $title;
            $data['content'] = $content;
            $data['summary'] = $summary;
            $data['thumb'] = $thumb;
            $data['cat_id'] = $cat_id;
            $data['tags_name'] = $tags;
            $data['status'] = $article['status'] == 1 ? 1 : 0;
            $data['is_email_noitce'] = $email_notice;
            $this->db->trans_begin();//开启事务
            $query1 = $this->db->where(array("id"=>$article['id']))->update("bbs_article",$data);
            //更新文章标签统计
            $tags ? $query2 = $this->update_tags($tags) : $query2 = 1;
            if($query1 && $query2){
                $this->db->trans_commit();//提交事务
                $mess['reqStatus'] = true;
                $mess['url'] = $article['status'] == 1 ? web_url("/p/".encrypt_article_id($article['id'])) : web_url("/p/upub/".encrypt_article_id($article['id']));
                $mess['errorMsg'] = "发布成功";
                echo JSON($mess);exit;
            }else{
                $this->db->trans_rollback();//事务回滚
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "发布失败，请稍后重试";
                echo JSON($mess);exit;
            }
        }
    }
    //保存草稿箱
    function add_box(){
        if($_POST){
            if(!$this->bbs_userinfo){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "您还未登录，请先登录哦";
                echo JSON($mess);exit;
            }
            $title = isset($_POST['artTitle']) ? trim($_POST['artTitle']) : "" ;//帖子名称
            $content = isset($_POST['artContent']) ? trim($_POST['artContent']) : "" ;//帖子内容
            $cat_id = isset($_POST['artCat']) ? trim($_POST['artCat']) : "" ;//帖子类别
            $tags = isset($_POST['artTag']) ? trim($_POST['artTag']) : "" ;//帖子标签
            $email_notice = isset($_POST['is_email']) ? trim($_POST['is_email']) : 0 ;//有评论是否邮件通知
            $draftNnumber = isset($_POST['draftNnumber']) ? trim($_POST['draftNnumber']) : 0 ;//有评论是否邮件通知
            
            $title = strip_tags($title);
            if($title == ""){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "标题不合法，请重新输入";
                echo JSON($mess);exit;
            }
            
            if($content == ""){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "请输入文章内容";
                echo JSON($mess);exit;
            }
            
            $allergicWord = file_get_contents("http://static.tan66.com/upfiles/files/badwords.txt");
            $allergicWord = str_replace(array("\r\n", "\r", "\n"),'',$allergicWord);
            $allergicWord= explode('|',$allergicWord);
            $info=0;
            $tinfo=0;
            $sensitive = "";
            for ($i=0;$i<count($allergicWord);$i++){  
                $check = substr_count($content, $allergicWord[$i]);
                $tcheck = substr_count($title,$allergicWord[$i]);
                if($check>0){
                    $sensitive .= $allergicWord[$i];
                    $info = $check;
                    break;
                }
                if($tcheck>0){
                    $sensitive .= $allergicWord[$i];
                    $tinfo = $tcheck;
                    break;;
                }
            }  
            if($info>0 || $tcheck>0){
                $errmes['reqStatus'] = false;
                $errmes['errorMsg'] = "检查您的文章里面有非法或敏感内容:<span class='error'>".$sensitive."</span>，请修正";
                $errmes['errorCode'] = 1003;
                echo JSON($errmes);exit;
            }
            $data = array();
            $data['title'] = $title;
            $data['content'] = $content;
            $data['cat_id'] = $cat_id;
            $data['tags_name'] = $tags;
            $data['create_time'] = time();
            $data['is_email_noitce'] = $email_notice;
            //判断是否存在草稿箱
            $flag = $this->db->select("*")->from("bbs_article_drafts")->where(array("draft_number"=>$draftNnumber))->get()->num_rows();
            if($flag){//更新草稿箱
                $result = $this->db->where('draft_number',$draftNnumber)->update("bbs_article_drafts", $data);
            }else{//插入草稿箱
                $data['authorid'] = $this->bbs_userinfo['user_id'];
                $data['draft_number'] = $draftNnumber;
                $this->db->insert("bbs_article_drafts", $data);
                $result = $this->db->insert_id();
            }
            if($result){
                $box_num = $this->db->select("*")->from("bbs_article_drafts")->where(array("authorid"=>$this->bbs_userinfo['user_id']))->get()->num_rows();
                $mess['reqStatus'] = true;
                $mess['boxNum'] = $box_num;
                $mess['errorMsg'] = "已保存草稿箱";
                echo JSON($mess);exit;
            }else{
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "保存失败，请稍后重试";
                echo JSON($mess);exit;
            }
        }
    }
    
    //保存草稿箱
    function save(){
        if($_POST){
            if(!$this->bbs_userinfo){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "您还未登录，请先登录哦";
                echo JSON($mess);exit;
            }
            $title = isset($_POST['artTitle']) ? trim($_POST['artTitle']) : "" ;//帖子名称
            $content = isset($_POST['artContent']) ? trim($_POST['artContent']) : "" ;//帖子内容
            $cat_id = isset($_POST['artCat']) ? trim($_POST['artCat']) : "" ;//帖子类别
            $tags = isset($_POST['artTag']) ? trim($_POST['artTag']) : "" ;//帖子标签
            $email_notice = isset($_POST['is_email']) ? trim($_POST['is_email']) : 0 ;//有评论是否邮件通知
            $draftNnumber = isset($_POST['draftNnumber']) ? trim($_POST['draftNnumber']) : 0 ;//有评论是否邮件通知
            
            $title = strip_tags($title);
            if($title == ""){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "标题不合法，请重新输入";
                echo JSON($mess);exit;
            }
            
            if($content == ""){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "请输入文章内容";
                echo JSON($mess);exit;
            }
            
            $allergicWord = file_get_contents("http://static.tan66.com/upfiles/files/badwords.txt");
            $allergicWord = str_replace(array("\r\n", "\r", "\n"),'',$allergicWord);
            $allergicWord= explode('|',$allergicWord);
            $info=0;
            $tinfo=0;
            for ($i=0;$i<count($allergicWord);$i++){  
                $check = substr_count($content, $allergicWord[$i]);
                $tcheck = substr_count($title,$allergicWord[$i]);
                if($check>0){
                    $info = $check;
                    break;
                }
                if($tcheck>0){
                    $tinfo = $tcheck;
                    break;;
                }
            }  
            if($info>0 || $tcheck>0){
                $errmes['reqStatus'] = false;
                $mess['errorMsg'] = "检查您的文章里面有非法或敏感内容，请修正";
                $errmes['errorCode'] = 1003;
                echo JSON($errmes);exit;
            }
            $data = array();
            $data['title'] = $title;
            $data['content'] = $content;
            $data['cat_id'] = $cat_id;
            $data['tags_name'] = $tags;
            $data['create_time'] = time();
            $data['is_email_noitce'] = $email_notice;
            //判断是否存在草稿箱
            $flag = $this->db->select("*")->from("bbs_article_drafts")->where(array("draft_number"=>$draftNnumber))->get()->row_array();
            if($flag){//更新草稿箱
                $result = $this->db->where('draft_number',$draftNnumber)->update("bbs_article_drafts", $data);
                $result = $flag['id'];
            }else{//插入草稿箱
                $data['authorid'] = $this->bbs_userinfo['user_id'];
                $data['draft_number'] = $draftNnumber;
                $this->db->insert("bbs_article_drafts", $data);
                $result = $this->db->insert_id();
            }
            if($result){
                $mess['reqStatus'] = true;
                $mess['url'] = web_url("p/view/".$result);
                $mess['errorMsg'] = "已保存草稿箱";
                echo JSON($mess);exit;
            }else{
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "保存失败，请稍后重试";
                echo JSON($mess);exit;
            }
        }
    }
    
    
    //更新文章标签统计
    private function update_tags($tags){
        $flag = 1;
        $tag_arr = explode(",", $tags);
        foreach ($tag_arr as $key=>$val){
            $tag = explode("_", $val);
            
            $sql = "UPDATE tan_bbs_article_tags SET use_count = use_count + 1 WHERE id = $tag[1];";
            $flag = $this->db->query($sql);
            if(!$flag){
                break;
            }
        }
        
        return $flag;
        
    }
    //删除草稿箱
    private function delete_draft($draft_number){
        $flag = 1;
        if($draft_number){
            $box_num = $this->db->select("*")->from("bbs_article_drafts")->where(array("draft_number"=>$draft_number))->get()->num_rows();
            if($box_num){
                $flag = $this->db->where('draft_number',$draft_number)->delete("bbs_article_drafts");
            }
        }
        return $flag;
    }
    //编辑文章
    function edit($article_id){
        $article_id = $article_id ? decrypt_article_id($article_id) : 0;
        $item = $this->db->query("select * from tan_bbs_article where id = ".$article_id." and status != 0 limit 1")->row_array();
        if(!$item || $item['authorid'] != $this->bbs_userinfo['user_id']){
            $this->assign("error", "没有符合的数据");
            $this->display('deleted/index.html');exit;
        }
        $tags_arr = array();
        if($item['tags_name']){
            $tags = explode(",", $item['tags_name']);
            foreach ($tags as $key=>$val){
                $val = explode("_", $val);
                $tags_arr[$val['1']] = $val[0];
            }
        }
        $item['tags'] = $tags_arr;
        $item['article_id'] = encrypt_article_id($article_id);
        //草稿箱数量
        $box_num = $this->db->select("*")->from("bbs_article_drafts")->where(array("authorid"=>$this->bbs_userinfo['user_id']))->get()->num_rows();
        $user_info = $this->db->select("email")->from("users")->where(array("user_id"=>$this->bbs_userinfo['user_id']))->get()->row_array();
        $user_email = $user_info['email'] ? email_formart($user_info['email']) : "";
        
        //热门文章
        $hot_arts = $this->hot_art();
        
        $this->assign("hot_arts", $hot_arts);
        $this->assign("item", $item);
        $this->assign("box_num", $box_num);
        $this->assign("user_email", $user_email);
        $this->display('post/edit.html');
    }
    function boxs($draft_id){
        $item = $this->db->select("*")->from("bbs_article_drafts")->where(array("id"=>$draft_id))->get()->row_array();
        if(!$item || $item['authorid'] != $this->bbs_userinfo['user_id']){
            web_redirect("post");
        }
        $tags_arr = array();
        if($item['tags_name']){
            $tags = explode(",", $item['tags_name']);
            foreach ($tags as $key=>$val){
                $val = explode("_", $val);
                $tags_arr[$val['1']] = $val[0];
            }
        }
        $item['tags'] = $tags_arr;
        //草稿箱数量
        $box_num = $this->db->select("*")->from("bbs_article_drafts")->where(array("authorid"=>$this->bbs_userinfo['user_id']))->get()->num_rows();
        $user_info = $this->db->select("email")->from("users")->where(array("user_id"=>$this->bbs_userinfo['user_id']))->get()->row_array();
        $user_email = $user_info['email'] ? email_formart($user_info['email']) : "";
        $tags = $this->db->select("*")->from("bbs_article_tags")->where(array("is_recommend"=>1))->order_by("sort desc")->get()->result_array();
        
        //热门文章
        $hot_arts = $this->hot_art();
        
        $this->assign("hot_arts", $hot_arts);
        $this->assign("tags", $tags);
        $this->assign("item", $item);
        $this->assign("draft_number", $item['draft_number']);
        $this->assign("box_num", $box_num);
        $this->assign("user_email", $user_email);
        $this->display('post/box.html');
    }
    
    function upload(){
        echo json_encode(array("txt"=>123));die;
    }
    
    //热门文章
    private function hot_art(){
        $list = $this->db->query("select id,title,commentnum from tan_bbs_article where hot = 1 and status = 1 and `show` = 1 order by sort desc limit 5")->result_array();
        foreach ($list as $key=>$val){
            $list[$key]['detail_url'] = web_url("p/".encrypt_article_id($val['id']));
        }
        return $list;
    }
}
